package com.st.api.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.st.api.bo.FacadeResult;
import com.st.api.bo.Page;
import com.st.api.bo.PullUserModel;
import com.st.api.constants.ReturnServiceCode;
import com.st.api.mq.MessageProduct;
import com.st.api.service.IMessageService;
import com.st.api.service.ISystemQueryService;
import com.st.api.util.StringUtils;

@Controller
@RequestMapping(value = "/system", produces = "application/json")
@Scope("prototype")
public class SystemQueryController extends BaseController{

	
	private static Logger logger = LoggerFactory.getLogger(SystemQueryController.class);
	
	@Autowired
	private ISystemQueryService systemQueryService;
	@Autowired
	private IMessageService messageService;
	@Autowired
	private MessageProduct mp;
	/**
	 * 更新生态圈和产品大类
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/updateEcInfo",method=RequestMethod.GET)
	public @ResponseBody FacadeResult updateEcInfo(HttpServletRequest request){
			
		
		
		/*	if(StringUtils.isNull(request.getParameter("ecid"))||
					StringUtils.isNull(request.getParameter("prodcat"))||
						StringUtils.isNull(request.getParameter("rolecode"))){
				
				return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
			}*/
			if(StringUtils.isNull(request.getParameter("rolecode"))){
				
				return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
			}
			//封装参数
			Map<String,Object> ecMap = new HashMap<String,Object>();
		
			if("690".equals(request.getParameter("rolecode"))||"RESEARCH".equals(request.getParameter("rolecode"))){
				
				ecMap.put("uid",  request.getParameter("uid"));
				systemQueryService.updateAllEcInfo(ecMap);
				
				
			}else{
				if(StringUtils.isNull(request.getParameter("ecid"))||
						StringUtils.isNull(request.getParameter("prodcat"))){
					
					return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
				}
				
				
				ecMap.put("uid", request.getParameter("uid"));
				ecMap.put("ecid", Integer.valueOf(request.getParameter("ecid")));
				ecMap.put("prodcat",  request.getParameter("prodcat"));
				
				systemQueryService.updateEcInfo(ecMap);
				
				
			}
			Map<String,Object> rcMap = new HashMap<String,Object>();
			rcMap.put("uid", request.getParameter("uid"));
			rcMap.put("rolecode", request.getParameter("rolecode"));
			
			systemQueryService.updateRcInfo(rcMap);
			
			return generateData(200,"success");
		
	}
	
	
	/**
	 * 获取生态圈列表
	 * @param pageSize
	 * @param currentPage
	 * @return
	 */
	@RequestMapping(value="/getEcList",method=RequestMethod.GET)
	public @ResponseBody FacadeResult getEcList(HttpServletRequest request){
	
			List<Object> ret = systemQueryService.getEcList();
			
			return generateData(ret);
	}
	/**
	 * 获取当前用户有权限的生态圈列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getEcListByRole",method=RequestMethod.GET)
	public @ResponseBody FacadeResult getEcListByRole(HttpServletRequest request){
	
			List<Object> ret = systemQueryService.getEcListByRole(request.getParameter("uid"));
			
			return generateData(ret);
	}
	
	
	
	/**
	 * 获取产品大类
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getProdCatList",method=RequestMethod.GET)
	public @ResponseBody FacadeResult getProdCatList(HttpServletRequest request){
	
		if(StringUtils.isNull(request.getParameter("ecid"))){
			
			return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
		}
		Map paramMap = StringUtils.getParameterMap(request);
		List<Object> ret = systemQueryService.getProdCatList(paramMap);
		return generateData(ret);
		
	}
	
	/**
	 * 获取产品大类
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getProdCatListByRole2",method=RequestMethod.GET)
	public @ResponseBody FacadeResult getProdCatList2(HttpServletRequest request){
	
		if(StringUtils.isNull(request.getParameter("ecid"))){
			
			return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
		}
		Map<String,Object> paramMap = new HashMap<String,Object>();
		
		paramMap.put("ecid", Integer.valueOf(request.getParameter("ecid")));
		
		paramMap.put("uid", request.getParameter("uid"));
		
		List<Object> ret = systemQueryService.getProdCatListByRole2(paramMap);
		return generateData(ret);
		
	}
	
	
	
	
	/**
	 * 获取产品大类列表（当前用户）
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getProdCatListByRole",method=RequestMethod.GET)
	public @ResponseBody FacadeResult getProdCatListByRole(HttpServletRequest request){
			
			Map<String,Object> paramMap = new HashMap<String,Object>();
			
			paramMap.put("ecid", Integer.valueOf(request.getParameter("ecid")));
			
			paramMap.put("uid", request.getParameter("uid"));
			
			
			
			List<Object> ret = systemQueryService.getProdCatListByRole(paramMap);
			
			return generateData(ret);
	}
	
	
	/**
	 * 获取收入等级
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getIncList",method=RequestMethod.GET)
	public @ResponseBody FacadeResult getIncList(HttpServletRequest request){
	
			List<Object> ret = systemQueryService.getIncList();
			
			return generateData(ret);
		
	}
	/**
	 * 获取用户信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getUserInfo",method=RequestMethod.GET)
	public @ResponseBody Map getUserInfo(HttpServletRequest request){
		
		//daqu list
		List<Object> capList = systemQueryService.getProdCatByUserCode(request.getParameter("uid"));
		
		//菜单列表
		List<Object> menuList = systemQueryService.getUserMenuByUserCode(request.getParameter("uid"));
		
		Map<String,Object> accessInfoMap = systemQueryService.getAccessInfoMap(request.getParameter("uid"));
		//组装accessInfo
		
		
		//组装用户信息usermap
		Map<String,Object> userMap = systemQueryService.getUserInfoByUserCode(request.getParameter("uid"));
		
		userMap.put("prod_cat", capList);
		
		userMap.put("usermenu",menuList);
		
		
		//组装returnMap
		Map<String,Object> returnMap = StringUtils.returnMap(200, "");
		
		returnMap.put("token", request.getParameter("token"));
		returnMap.put("userinfo",userMap);
		returnMap.put("accessinfo",accessInfoMap);
		
		return returnMap;
	}
	/**
	 * 获取产品系列
	 * @param request
	 * @return
	 */
	
	@RequestMapping(value="/getProdSeries",method=RequestMethod.GET)
	public @ResponseBody FacadeResult getProdSeries(HttpServletRequest request){
	
			if(StringUtils.isNull(request.getParameter("prodcat"))){
				
				return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
			}
			List<Object> ret = systemQueryService.getProdSeries(request.getParameter("prodcat"));
			
			return generateData(ret);
		
	}
	
	/**
	 * 获取省份列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getProvince",method=RequestMethod.GET)
	public @ResponseBody FacadeResult getProvince(HttpServletRequest request){
	
			List<Object> ret = systemQueryService.getProvince();
			return generateData(ret);
			
	}
	
	/**
	 * 获取用户职能列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getRoleList",method=RequestMethod.GET)
	public @ResponseBody FacadeResult getRoleList(HttpServletRequest request){
	
			List<Object> ret = systemQueryService.getRoleList();
			
			return generateData(ret);
			
	}
	
	
	@RequestMapping(value="/sendMail",method=RequestMethod.GET)
	public @ResponseBody FacadeResult sendMail(HttpServletRequest request) throws UnsupportedEncodingException{
	
		if(	StringUtils.isNull(request.getParameter("subject"))||
					StringUtils.isNull(request.getParameter("content"))||
						StringUtils.isNull(request.getParameter("condition"))||
							StringUtils.isNull(request.getParameter("dt"))||
								StringUtils.isNull(request.getParameter("num"))){
			
			return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
			
		}
		Map paramMap = StringUtils.getParameterMap(request);
		if(paramMap.get("num")!=null&&!"".equals(paramMap.get("num"))&&!"null".equals(paramMap.get("num"))&&!"undefined".equals(paramMap.get("num"))){
			
			String [] mobiles = paramMap.get("num").toString().split(",");
			paramMap.put("mobiles", mobiles);
			
		}
		//process param condition 
		Map<String,Object> conditionMap  = StringUtils.jsonStrToObjMap(URLDecoder.decode(request.getParameter("condition"), "UTF-8"));
		
		if(conditionMap.get("series")!=null&&!"".equals(conditionMap.get("series"))&&!"null".equals(conditionMap.get("series"))&&!"undefined".equals(conditionMap.get("series"))){
			
			String[] series = conditionMap.get("series").toString().split(",");
			
			conditionMap.put("series", series);
			
		}
		if(conditionMap.get("cities")!=null&&!"".equals(conditionMap.get("cities"))&&!"null".equals(conditionMap.get("cities"))&&!"undefined".equals(conditionMap.get("cities"))){
			
			String[] cities = conditionMap.get("cities").toString().split(",");
			
			conditionMap.put("cities", cities);
			
		}
		List<Map> userMapList = new ArrayList<>();
		conditionMap.put("inviteCount", paramMap.get("inviteCount"));
		if("random".equals(paramMap.get("randomFlag"))){
			//随机查询前N条
			
			userMapList = systemQueryService.getUserListByConditionRandom(conditionMap);
		}else{
			 userMapList = systemQueryService.getUserListByCondition(conditionMap);
		}
		
		
		if(userMapList.size()>0){
			paramMap.put("dt", StringUtils.strToDate((String)paramMap.get("dt"), "yyyy-MM-dd"));
			messageService.sendMessage(userMapList,paramMap);
		}
	
		
		
		//Map returnMap = StringUtils.returnMap(200, "");
		
		
			
		return generateData(null);
			
	}
	
	//web端接口    -----start------
	/**
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getSysUserList")
	public @ResponseBody FacadeResult getSysUserList(HttpServletRequest request){
		
		Map<String,Object> paramMap = StringUtils.getParameterMap(request);
		//page param
		if(StringUtils.isNull(request.getParameter("num"))){
			paramMap.put("num","1");
		}
		if(StringUtils.isNull(request.getParameter("size"))){
			paramMap.put("size","10");
		}
		if(!StringUtils.isNull((String)paramMap.get("userName"))){
			paramMap.put("userName", URLDecoder.decode((String) paramMap.get("userName")));
		}
		if(!StringUtils.isNull((String)paramMap.get("deptName"))){
			paramMap.put("deptName", URLDecoder.decode((String) paramMap.get("deptName")));
		}
		Page page = new Page(Integer.valueOf((String)paramMap.get("num")),Integer.valueOf((String)paramMap.get("size")));
		page = systemQueryService.getSysUserList(page,paramMap);
		List<Object> ret = page.getResult();
		return generateData(ret,page.getTotal());
	}
	
	@RequestMapping("/getSysUserRole")
	public @ResponseBody FacadeResult getSysUserRole(HttpServletRequest request){
		if(StringUtils.isNull(request.getParameter("usercode"))){
			
			return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
		}
		
		List<Object> ret = systemQueryService.getSysUserRole(request.getParameter("usercode"));
		return generateData(ret);
	}

	/**
	 * 更新用户角色
	 * @param request
	 * @return
	 */
	
	@RequestMapping("/updateUserRole")
	public @ResponseBody FacadeResult updateUserRole(HttpServletRequest request){
		
		if(StringUtils.isNull(request.getParameter("roles"))){
			
			return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
		}
		
		Map<String,Object> paramMap = StringUtils.getParameterMap(request);
		List<Map> roleMapList = new ArrayList<Map>();
		//是否有审核人权限
		boolean hasSHMPower = false;
		if(paramMap.get("roles")!=null&&!"".equals(paramMap.get("roles"))&&!"null".equals(paramMap.get("roles"))&&!"undefined".equals(paramMap.get("roles"))){
			
			String[] roles = paramMap.get("roles").toString().split(",");
			//判断审核人角色是否在数组中
			hasSHMPower = StringUtils.isInArr("SHM", roles);
			
			for(int i=0;i<roles.length;i++){
				Map<String,Object> roleMap = new HashMap<String,Object>();
				roleMap.put("usercode",paramMap.get("usercode") );
				roleMap.put("rolecode", roles[i]);
				roleMapList.add(roleMap);
			}
			
		}
		systemQueryService.updateUserRoleAdvice(request.getParameter("usercode"),roleMapList,hasSHMPower);
		return generateData(null);
	}
	 
	@RequestMapping("/delSysUser")
	public @ResponseBody FacadeResult delSysUser(HttpServletRequest request){
		if(StringUtils.isNull(request.getParameter("usercode"))){
			
			return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
		}
		
		systemQueryService.delSysUserAdvice(request.getParameter("usercode"));
		return generateData(null);
	}
	
	/*@RequestMapping("/userUseInfo")
	public @ResponseBody FacadeResult userUseInfo(HttpServletRequest request){
		if(StringUtils.isNull(request.getParameter("datefrom"))||
				StringUtils.isNull(request.getParameter("dateto"))){
			
			return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
		}
		Map<String,Object> paramMap = StringUtils.getParameterMap(request);
		List<Object> deptUseTop5 = systemQueryService.getDeptUseTop5(paramMap);
		
		List<Map> ret = new ArrayList<Map>();
		for(int i=0;i<deptUseTop5.size();i++){
			Map<String,Object> dataMap = new HashMap<String,Object>();
			String deptName = (String) deptUseTop5.get(i);
			paramMap.put("deptName", deptName);
			List<Object> userUseList = systemQueryService.userUseInfo(paramMap);
			dataMap.put("deptName", deptName);
			dataMap.put("monthValue", userUseList);
			ret.add(dataMap);
		}
		
		return generateData(ret);
	}*/
	
	@RequestMapping("/userUseInfo")
	public @ResponseBody FacadeResult userUseInfo(HttpServletRequest request){
		if(StringUtils.isNull(request.getParameter("datefrom"))||
				StringUtils.isNull(request.getParameter("dateto"))){
			
			return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
		}
		Map<String,Object> paramMap = StringUtils.getParameterMap(request);
		List<Object> roleMapList = systemQueryService.getRoleList();
		
		List<Map> ret = new ArrayList<Map>();
		for(int i=0;i<roleMapList.size();i++){
			Map<String,Object> dataMap = new HashMap<String,Object>();
			String roleName = (String) ((HashMap) roleMapList.get(i)).get("name");
			paramMap.put("roleName", roleName);
			List<Object> userUseList = systemQueryService.userRoleUseInfo(paramMap);
			dataMap.put("roleName", roleName);
			dataMap.put("monthValue", userUseList);
			ret.add(dataMap);
		}
		
		return generateData(ret);
	}
	
	
	@RequestMapping("/increaseUserInfo")
	public @ResponseBody FacadeResult increaseUserInfo(HttpServletRequest request){
		if(StringUtils.isNull(request.getParameter("datefrom"))||
				StringUtils.isNull(request.getParameter("dateto"))){
			
			return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
		}
		Map<String,Object> paramMap = StringUtils.getParameterMap(request);
		List<Object> roleMapList = systemQueryService.getRoleList();
		
		List<Map> ret = new ArrayList<Map>();
		for(int i=0;i<roleMapList.size();i++){
			Map<String,Object> dataMap = new HashMap<String,Object>();
			String roleName = (String) ((HashMap) roleMapList.get(i)).get("name");
			paramMap.put("roleName", roleName);
			List<Object> userUseList = systemQueryService.increaseUserRoleInfo(paramMap);
			dataMap.put("roleName", roleName);
			dataMap.put("monthValue", userUseList);
			ret.add(dataMap);
		}
		
		return generateData(ret);
	}
	
	
	/*@RequestMapping("/increaseUserInfo")
	public @ResponseBody FacadeResult increaseUserInfo(HttpServletRequest request){
		if(StringUtils.isNull(request.getParameter("datefrom"))||
				StringUtils.isNull(request.getParameter("dateto"))){
			
			return generateException(ReturnServiceCode.CHECK_DATA_ERROR);
		}
		Map<String,Object> paramMap = StringUtils.getParameterMap(request);
		List<Object> increaseTop5 = systemQueryService.getIncreaseUserTop5(paramMap);
		
		List<Map> ret = new ArrayList<Map>();
		for(int i=0;i<increaseTop5.size();i++){
			Map<String,Object> dataMap = new HashMap<String,Object>();
			String deptName = (String) increaseTop5.get(i);
			paramMap.put("deptName", deptName);
			List<Object> userUseList = systemQueryService.increaseUserInfo(paramMap);
			dataMap.put("deptName", deptName);
			dataMap.put("monthValue", userUseList);
			ret.add(dataMap);
		}
		
		return generateData(ret);
	}
	*/
	
	
	
}
